<?php
/**
 * Created by PhpStorm.
 * User: wangjie
 * Date: 2021/01/22
 * Time: 17:49
 */
namespace App\Api\Controllers\YinSheng;


use App\Api\Controllers\BaseController;
use App\Api\Controllers\WftPay\BaseController as WftPayBaseController;
use App\Common\PaySuccessAction;
use App\Common\RefundSuccessAction;
use App\Models\MerchantWalletDetail;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\RefundOrder;
use App\Models\UserWalletDetail;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Schema;

class NotifyController extends BaseController
{
    //银盛支付 支付回调
    public function pay_notify_url(Request $request)
    {
        try {
            $original_data = $request->getContent();
            Log::info('银盛支付支付-原始回调');
            Log::info($original_data);

            if ($original_data) {
                $data = json_decode($original_data, true);
            }

            if (isset($data['out_trade_no'])) {
                $out_trade_no = $data['out_trade_no']; //银盛支付合作商户网站唯一订单号

                $day = date('Ymd', time());
                $table = 'orders_' . $day;
                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                } else {
                    $order = Order::where('out_trade_no', $out_trade_no)->first();
                    if (!$order) {
                        $order = Order::where('trade_no', $out_trade_no)->first();
                    }
                }

                //订单存在
                if ($order) {
                    //系统订单未成功
                    if ($order->pay_status == 2) {
                        $trade_no = isset($data['trade_no']) ? $data['trade_no'] : ""; //可空,该交易在银盛支付系统中的交易流水号
                        $pay_time = date('Y-m-d H:i:s', strtotime($data['time_end']));
                        $buyer_pay_amount = isset($data['total_amount']) ? $data['total_amount']: $order->total_amount; //可空,该笔订单的资金总额，单位为RMB-Yuan。取值范围为[0.01，100000000.00]，精确到小数点后两位
                        $settlement_amount = isset($data['settlement_amount']) ? $data['settlement_amount']: ''; //可空,结算金额
                        $buyer_pay_amount = number_format($buyer_pay_amount, 2, '.', '');
                        $buyer_id = isset($data['buyer_user_id']) ? $data['buyer_user_id'] : ""; //可空,支付宝用户Uid
                        $buyer_logon_id = isset($data['buyer_logon_id']) ? $data['buyer_logon_id'] : ""; //可空,支付宝账户
                        $coupon_info = isset($data['coupon_info']) ? $data['coupon_info'] : ""; //可空,优惠信息coupon_info优惠信息活动对象为多个时,coupon_info中就有多方优惠信息,spnsrId出资方,值为1时,银联出资;值为 2时,付款方出资;值为3时,商户出资.offstAmt优惠金额
                        $card_type = isset($data['card_type']) ? $data['card_type']: ''; //可空,卡类型,credit:信用卡;debit:借记卡

                        if ($data['trade_status'] == 'TRADE_SUCCESS') {
                            $pay_status = 1;
                            $pay_status_desc = '交易成功';
                        } elseif ($data['trade_status'] == 'TRADE_CLOSED') {
                            $pay_status = 4;
                            $pay_status_desc = '客户主动关闭订单';
                        } elseif ($data['trade_status'] == 'WAIT_BUYER_PAY') {
                            $pay_status = 2;
                            $pay_status_desc = '等待买家付款';
                        } elseif ($data['trade_status'] == 'TRADE_PROCESS') {
                            $pay_status = 2;
                            $pay_status_desc = '交易正在处理中';
                        } elseif ($data['trade_status'] == 'TRADE_PART_REFUND') {
                            $pay_status = 6;
                            $pay_status_desc = '部分退款成功';
                        } elseif ($data['trade_status'] == 'TRADE_ALL_REFUND') {
                            $pay_status = 6;
                            $pay_status_desc = '全部退款成功';
                        } else {
                            $pay_status = 2;
                            $pay_status_desc = '等待支付';
                        }

                        $in_data = [
                            'status' => '1',
                            'pay_status' => $pay_status,
                            'pay_status_desc' => $pay_status_desc,
                            'pay_time' => $pay_time,
                            'buyer_pay_amount' => $buyer_pay_amount
                        ];
                        if ($buyer_id) $in_data['buyer_id'] = $buyer_id;
                        if ($buyer_logon_id) $in_data['buyer_logon_id'] = $buyer_logon_id;
                        if ($trade_no) $in_data['trade_no'] = $trade_no;
                        if ($settlement_amount) $in_data['settlement_amount'] = $settlement_amount;
                        if ($card_type) $in_data['payment_method'] = $card_type; //credit：信用卡 pcredit：花呗（仅支付宝） debit：借记卡 balance：余额 unknown：未知
                        $this->update_day_order($in_data, $out_trade_no);

                        if (strpos($out_trade_no, 'scan')) {

                        } else {
                            //支付成功后的动作
                            $data = [
                                'ways_type' => $order->ways_type,
                                'company' => $order->company,
                                'ways_type_desc' => $order->ways_type_desc,
                                'source_type' => '14000',//返佣来源
                                'source_desc' => '银盛支付',//返佣来源说明
                                'total_amount' => $order->total_amount,
                                'out_trade_no' => $order->out_trade_no,
                                'other_no' => $order->other_no,
                                'rate' => $order->rate,
                                'fee_amount' => $order->fee_amount,
                                'merchant_id' => $order->merchant_id,
                                'store_id' => $order->store_id,
                                'user_id' => $order->user_id,
                                'config_id' => $order->config_id,
                                'store_name' => $order->store_name,
                                'ways_source' => $order->ways_source,
                                'pay_time' => $pay_time,
                                'device_id' => $order->device_id,
                            ];
                            PaySuccessAction::action($data);
                        }
                    }
                }
            }

            return 'success';
        } catch (\Exception $ex) {
            Log::info('银盛支付支付异步报错');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }


    //todo:银盛支付 退款回调
    public function refund_notify_url(Request $request)
    {
        try {
            $data = $request->getContent();
            Log::info('银盛支付退款-回调-原始数据');
            Log::info($data);

            if (isset($data['out_trade_no'])) {
                $out_trade_no = $data['out_trade_no'];
                $a = array('a', '_', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
                $b = str_ireplace($a, "", $out_trade_no);
                $day = substr($b, 0, 8);
                $table = 'orders_' . $day;

                $out_trade_no = substr($out_trade_no, 0, strlen($out_trade_no)-4);

                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $out_trade_no)->first();
                } else {
                    $order = Order::where('out_trade_no', $out_trade_no)->first();
                }

                //订单存在
                if ($order && $order->pay_status == '1') {
                    if ($data['result_code'] == "0") {
                        $refund_amount = $data["refund_fee"];
                        $update_data = [
                            'status' => 6,
                            'pay_status' => 6,
                            'pay_status_desc' => '已退款',
                            'refund_amount' => $order->refund_amount + $refund_amount,
                            'fee_amount' => 0,
                        ];
                        if (Schema::hasTable($table)) {
                            DB::table($table)->where('out_trade_no', $out_trade_no)
                                ->update($update_data);
                        } else {
                           Order::where('out_trade_no', $out_trade_no)
                                ->update($update_data);
                        }
                        if (Schema::hasTable('order_items')) {
                            OrderItem::where('out_trade_no', $out_trade_no)->update($update_data);
                        }

                        RefundOrder::create([
                            'ways_source' => $order->ways_source,
                            'type' => $order->ways_type,
                            'refund_amount' => $refund_amount, //退款金额
                            'refund_no' => $data['refund_id'], //退款单号
                            'store_id' => $order->store_id,
                            'merchant_id' => $order->merchant_id,
                            'out_trade_no' => $order->out_trade_no,
                            'trade_no' => $order->other_no
                        ]);
                        //退款成功后的操作
                        RefundSuccessAction::action([
                            'out_trade_no'=>$out_trade_no,
                            'refund_no' =>$data['refund_id'], //退款单号
                        ]);
                        //返佣去掉
                        UserWalletDetail::where('out_trade_no', $order->out_trade_no)->update([
                            'settlement' => '03',
                            'settlement_desc' => '退款订单',
                        ]);
                        MerchantWalletDetail::where('out_trade_no', $order->out_trade_no)->update([
                            'settlement' => '03',
                            'settlement_desc' => '退款订单',
                        ]);
                    }
                }
            }

            return 'success';
        } catch (\Exception $ex) {
            Log::info('银盛支付-退款回调异步报错');
            Log::info($ex->getMessage().' | '.$ex->getFile().' | '.$ex->getLine());
        }
    }

    //pos 回调
    public function pos (Request $request)
    {
        echo 1;
    }

}
